<template>
  <div>
    <h3>工单管理表格</h3>
    <el-input
        placeholder="请输入业务名或客户名"
        v-model="searchQuery"
        style="width: 200px; margin-right: 10px;"
        clearable
        @clear="fetchWorkOrders"
    />
    <el-button type="primary" @click="searchWorkOrders">搜索</el-button>
    <el-button type="primary" @click="openDialog">添加工单</el-button>
    <el-table :data="workOrders" style="width: 100%; margin-top: 20px;">
      <!-- 表格列定义 -->
      <el-table-column prop="id" label="ID" width="180"></el-table-column>
      <el-table-column prop="operationName" label="业务名称" width="180"></el-table-column>
      <el-table-column prop="customerName" label="客户名称" width="180"></el-table-column>
      <el-table-column prop="status" label="状态" width="180"></el-table-column>
      <el-table-column prop="person" label="指派人" width="180"></el-table-column>
      <el-table-column prop="area" label="区域" width="180"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column label="操作" width="180">
        <template v-slot="scope">
          <el-button size="small" @click="editWorkOrder(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteWorkOrder(scope.row.id)">删除</el-button>
          <el-button size="small" @click="assignWorkOrder(scope.row)">派单</el-button>
          <el-button size="small" @click="receiveWorkOrder(scope.row.id)">收单</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="isEdit ? '编辑工单' : '添加工单'" v-model="dialogVisible">
      <el-form :model="newWorkOrder" :rules="rules" ref="workOrderForm">
        <!-- 表单项定义 -->
        <el-form-item label="业务名称" :label-width="formLabelWidth" prop="operationName">
          <el-select v-model="newWorkOrder.operationName" placeholder="请选择业务">
            <el-option v-for="operation in operations" :key="operation.id" :label="operation.name" :value="operation.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" :label-width="formLabelWidth" prop="customerName">
          <el-select v-model="newWorkOrder.customerName" placeholder="请选择客户">
            <el-option v-for="customer in customers" :key="customer.id" :label="customer.name" :value="customer.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth" prop="status">
          <el-select v-model="newWorkOrder.status" placeholder="请选择状态">
            <el-option label="未派单" value="未派单"></el-option>
            <el-option label="已派单" value="已派单"></el-option>
            <el-option label="已收单" value="已收单"></el-option>
            <el-option label="已回单" value="已回单"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域" :label-width="formLabelWidth" prop="area">
          <el-select v-model="newWorkOrder.area" placeholder="请选择区域">
            <el-option v-for="area in areas" :key="area.id" :label="area.name" :value="area.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指派人" :label-width="formLabelWidth" prop="person">
          <el-select v-model="newWorkOrder.person" placeholder="请选择指派人">
            <el-option v-for="person in persons" :key="person.id" :label="person.name" :value="person.name"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth" prop="createTime">
          <el-date-picker v-model="newWorkOrder.createTime" type="date" placeholder="选择创建时间"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addOrUpdateWorkOrder">确定</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="派单" v-model="assignDialogVisible">
      <el-form :model="assignWorkOrderData" ref="assignForm">
        <el-form-item label="指派人" :label-width="formLabelWidth">
          <el-select v-model="assignWorkOrderData.person" placeholder="请选择指派人">
            <el-option v-for="person in persons" :key="person.id" :label="person.name" :value="person.name"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="assignWorkOrderConfirm">确定</el-button>
        <el-button @click="assignDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      workOrders: [],
      operations: [],
      customers: [],
      areas: [],
      persons: [],
      dialogVisible: false,
      assignDialogVisible: false,
      isEdit: false,
      searchQuery: '',
      newWorkOrder: {
        operationName: '',
        customerName: '',
        status: '',
        area: '',
        person: '',
        createTime: ''
      },
      assignWorkOrderData: {
        id: '',
        person: ''
      },
      formLabelWidth: '120px',
      rules: {
        operationName: [{ required: true, message: '请选择业务名称', trigger: 'change' }],
        customerName: [{ required: true, message: '请选择客户名称', trigger: 'change' }],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        area: [{ required: true, message: '请选择区域', trigger: 'change' }],
        person: [{ required: true, message: '请选择指派人', trigger: 'change' }],
        createTime: [{ required: true, message: '请选择创建时间', trigger: 'change' }]
      }
    };
  },
  created() {
    this.fetchWorkOrders();
    this.fetchOperations();
    this.fetchCustomers();
    this.fetchAreas();
    this.fetchPersons();
  },
  methods: {
    fetchWorkOrders() {
      axios.get('http://localhost:8081/api/workorder/getall')
          .then(response => {
            this.workOrders = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the work orders!", error);
          });
    },
    fetchOperations() {
      axios.get('http://localhost:8081/api/workorder/operations')
          .then(response => {
            this.operations = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the operations!", error);
          });
    },
    fetchCustomers() {
      axios.get('http://localhost:8081/api/workorder/customers')
          .then(response => {
            this.customers = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the customers!", error);
          });
    },
    fetchAreas() {
      axios.get('http://localhost:8081/api/workorder/areas')
          .then(response => {
            this.areas = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the areas!", error);
          });
    },
    fetchPersons() {
      axios.get('http://localhost:8081/api/workorder/persons')
          .then(response => {
            this.persons = response.data;
          })
          .catch(error => {
            console.error("There was an error fetching the persons!", error);
          });
    },
    searchWorkOrders() {
      axios.get('http://localhost:8081/api/workorder/get', {
        params: {
          operationName: this.searchQuery,
          customerName: this.searchQuery
        }
      })
          .then(response => {
            this.workOrders = response.data;
          })
          .catch(error => {
            console.error("There was an error searching the work orders!", error);
          });
    },
    openDialog() {
      this.isEdit = false;
      this.dialogVisible = true;
      this.resetWorkOrder();
    },
    editWorkOrder(workOrder) {
      this.isEdit = true;
      this.dialogVisible = true;
      this.newWorkOrder = { ...workOrder };
    },
    addOrUpdateWorkOrder() {
      this.$refs.workOrderForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            axios.put('http://localhost:8081/api/workorder/update', this.newWorkOrder)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchWorkOrders();
                  this.resetWorkOrder();
                  ElMessage.success('工单更新成功');
                })
                .catch(error => {
                  console.error("There was an error updating the work order!", error);
                  ElMessage.error('工单更新失败');
                });
          } else {
            axios.post('http://localhost:8081/api/workorder/add', this.newWorkOrder)
                .then(() => {
                  this.dialogVisible = false;
                  this.fetchWorkOrders();
                  this.resetWorkOrder();
                  ElMessage.success('工单添加成功');
                })
                .catch(error => {
                  console.error("There was an error adding the work order!", error);
                  ElMessage.error('工单添加失败');
                });
          }
        }
      });
    },
    deleteWorkOrder(id) {
      axios.delete(`http://localhost:8081/api/workorder/delete/${id}`)
          .then(() => {
            this.fetchWorkOrders();
            ElMessage.success('工单删除成功');
          })
          .catch(error => {
            console.error("There was an error deleting the work order!", error);
            ElMessage.error('工单删除失败');
          });
    },
    assignWorkOrder(workOrder) {
      this.assignWorkOrderData.id = workOrder.id;
      this.assignDialogVisible = true;
    },
    assignWorkOrderConfirm() {
      axios.put('http://localhost:8081/api/workorder/assign', null, {
        params: {
          id: this.assignWorkOrderData.id,
          person: this.assignWorkOrderData.person
        }
      })
          .then(() => {
            this.assignDialogVisible = false;
            this.fetchWorkOrders();
            ElMessage.success('工单派单成功');
          })
          .catch(error => {
            console.error("There was an error assigning the work order!", error);
            ElMessage.error('工单派单失败');
          });
    },
    receiveWorkOrder(id) {
      axios.put('http://localhost:8081/api/workorder/receive', null, {
        params: { id }
      })
          .then(() => {
            this.fetchWorkOrders();
            ElMessage.success('工单收单成功');
          })
          .catch(error => {
            console.error("There was an error receiving the work order!", error);
            ElMessage.error('工单收单失败');
          });
    },
    resetWorkOrder() {
      this.newWorkOrder = {
        operationName: '',
        customerName: '',
        status: '',
        area: '',
        person: '',
        createTime: ''
      };
    }
  }
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>
